var gulp = require('gulp');
var args = require('yargs').argv;
var colors = require('colors');
var exec = require('child_process').exec;
var fs = require('fs');

var mappings = {
    'batchService': {
        'source': 'specification/batch/data-plane/Microsoft.Batch/stable/2018-08-01.7.1/BatchService.json',
        'package': 'com.microsoft.azure.batch.protocol',
        'fluent': false,
        'args': '-FT 1'
    }
};

gulp.task('default', function() {
    console.log("Usage: gulp codegen [--spec-root <swagger specs root>] [--autorest <autorest info>] [--modeler <modeler name>] [--autorest-args <AutoRest arguments>]\n");
    console.log("--spec-root");
    console.log("\tRoot location of Swagger API specs, default value is \"https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master\"");
    console.log("--autorest\n\tThe version of AutoRest. E.g. 0.15.0, or the location of AutoRest repo, E.g. E:\\repo\\autorest");
    console.log("--modeler\n\tSpecifies which modeler to use. Default is 'Swagger'");
    console.log("--autorest-args\n\tPasses additional argument to AutoRest generator");
});

var specRoot = args['spec-root'] || "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/current";
var projects = 'batchService'; // default
var autoRestVersion = '1.2.2'; // default
if (args['autorest'] !== undefined) {
    autoRestVersion = args['autorest'];
}
var modeler = 'Swagger'; // default
if (args['modeler'] !== undefined) {
	modeler = args['modeler'];
}
var autoRestArgs = args['autorest-args'];
var autoRestExe;

gulp.task('codegen', function(cb) {
    autoRestExe = 'autorest';
    handleInput(projects, cb);
});

var handleInput = function(projects, cb) {
    if (projects === undefined) {
        Object.keys(mappings).forEach(function(proj) {
            codegen(proj, cb);
        });
    } else {
        projects.split(",").forEach(function(proj) {
            proj = proj.replace(/\ /g, '');
            if (mappings[proj] === undefined) {
                console.error('Invalid project name "' + proj + '"!');
                process.exit(1);
            }
            codegen(proj, cb);
        });
    }
}

var codegen = function(project, cb) {
    var outputDir = 'src/main/java/' + mappings[project].package.replace(/\./g, '/');
    deleteFolderRecursive(outputDir);
    console.log('Generating "' + project + '" from spec file ' + specRoot + '/' + mappings[project].source);
    var generator = '--fluent ';
    if (mappings[project].fluent !== null && mappings[project].fluent === false) {
        generator = '';
    }
    cmd = autoRestExe + ' --java ' +
                        ' --azure-arm ' + 
                        ' --namespace=' + mappings[project].package + 
                        ' --input-file=' + specRoot + '/' + mappings[project].source + 
                        ' --java.output-folder=' + 'src/main/java/' + mappings[project].package.replace(/\./g, '/') + 
                        ' --license-header=MICROSOFT_MIT_NO_CODEGEN' +
                        ' -' + autoRestArgs;
    if (mappings[project].args !== undefined) {
        cmd = cmd + ' ' + mappings[project].args;
    }
    console.log('Command: ' + cmd);
    exec(cmd, function(err, stdout, stderr) {
        console.log(stdout);
        console.error(stderr);
    });
};

var deleteFolderRecursive = function(path) {
    var header = "Code generated by Microsoft (R) AutoRest Code Generator";
    if(fs.existsSync(path)) {
        fs.readdirSync(path).forEach(function(file, index) {
            var curPath = path + "/" + file;
            if(fs.lstatSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursive(curPath);
            } else { // delete file
                var content = fs.readFileSync(curPath).toString('utf8');
                if (content.indexOf(header) > -1) {
                    fs.unlinkSync(curPath);
                }
            }
        });
    }
};